package com.juicygames.framework.touch;

import java.util.ArrayList;
import java.util.List;

import android.view.MotionEvent;

import com.juicygames.framework.action.EntityDestroyedAction;
import com.juicygames.framework.exception.GamePartNotFound;
import com.juicygames.framework.gamepart.GameHandler;
import com.juicygames.framework.property.space.TouchBoundingBox;

public class EntityTouchService extends GameHandler<TouchAction> {
	private static final String LOGTAG = EntityTouchService.class.getName();
	
	private List<Touchable> touchables;
	private GameHandler<WorldTouchAction> nothingTouchedHandler = null;
	
	public EntityTouchService() {
		super();
		touchables = new ArrayList<Touchable>();
	}
	
	public void load() {
		addPart(new EntityDestroyedHandler(touchables));
	}
	
	public Class<TouchAction> getActionClassHandled() {
		return TouchAction.class;
	}
	
	public <G extends GameHandler<EntityTouchAction>> void register(G handler) {
		
		try {
			Touchable touchable = new Touchable();
			touchable.handler = handler;
			touchable.entity = handler.getSelf();
			touchable.boundingBox = touchable.entity.getPart(TouchBoundingBox.class);
			
			touchables.add(touchable);
			
			
		} catch (GamePartNotFound e) {
			throw new IllegalArgumentException("Part not found when regestering part for touch", e);
		}
	}
	
	public <G extends GameHandler<WorldTouchAction>> void registerNothingTouched(G handler) {
		nothingTouchedHandler = handler;
	}
	
	public void handle(TouchAction touch) {
		boolean touchHandled = false;
		
		MotionEvent event = touch.getEvent();
		
		if (event.getAction() != MotionEvent.ACTION_MOVE) {
			
			EntityTouchAction entityTouch = EntityTouchAction.getInstance(event);
			
			for (Touchable touchable : touchables) {
				
				if (touchable.boundingBox.get().contains((int)event.getX(), (int)event.getY())) {
					
					touchable.handler.handle(entityTouch);
					
					touchHandled = true;
				}
			}
		}
		
		if (nothingTouchedHandler != null) {
			
			WorldTouchAction worldTouch = WorldTouchAction.getInstance(event);
			
			worldTouch.setEntityWasTouched(touchHandled);
			
			nothingTouchedHandler.handle(worldTouch);
		}
	}
	

	public class EntityDestroyedHandler extends GameHandler<EntityDestroyedAction> {
		
		private List<Touchable> touchables;
		
		public EntityDestroyedHandler(List<Touchable> touchables) {
			this.touchables = touchables;
		}
		
		public void load() {
			groundHandler();
		}
		
		public Class<EntityDestroyedAction> getActionClassHandled() {
			return EntityDestroyedAction.class;
		}
		
		public void handle(EntityDestroyedAction entityDestroyed) {
			for (Touchable touchable : touchables) {
				if (touchable.entity == entityDestroyed.getEntity()) {
					touchables.remove(touchable);
				}
			}
		}
	}

}
